package yxy.game.pm2.module.task;

import java.util.Collection;
import java.util.Map;

import yxy.game.pm2.bean.Currency;
import yxy.game.pm2.bean.mq.CCReason;
import yxy.game.pm2.bean.pubsub.TaskPublisher;
import yxy.game.pm2.bean.task.Task;
import yxy.game.pm2.bean.task.TaskType;
import yxy.game.pm2.message.TaskMessage;
import yxy.game.pm2.module.CurrencyHandle;
import yxy.game.pm2.module.daily.DailyModule;

public class TaskHandle {
	static public void handle(String playerCode, TaskType type, long value, int condition) {
		// XXX 临时增加的处理 避免跨日后 日常奖励没有还原
		DailyModule.get(playerCode);

		boolean hasfinished = false;
		try {
			if (Task.lockTask(playerCode)) {
				Map<String, Task> tasks = Task.getByType(playerCode, type);
				for (Task task : tasks.values()) {
					switch (type.getCountType()) {
					case 累计:
						task.count(value, condition);
						break;
					case 达到:
						task.check(value, condition);
						break;
					}
					if (task.isFinish()) {
						hasfinished = true;
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			Task.unlockTask(playerCode);
		}
		if (hasfinished) {
			TaskPublisher.getInstance().publish(playerCode);
		}
	}

	public static void handle(String playerCode, TaskType type, long value) {
		handle(playerCode, type, value, -1);
	}

	static public TaskMessage.Task packTask(Task task) {
		TaskMessage.Task.Builder builder = TaskMessage.Task.newBuilder();
		builder.setCode(task.getCode());
		builder.setDataId(task.getDataId());
		builder.setProgress(task.progress());
		builder.setFinish(task.isFinish());
		builder.setReward(task.isReward());
		return builder.build();
	}

	public Collection<Currency> rewardTask(String playerCode, CCReason reason, Task task) {
		Collection<Currency> rewards = task.reward();
		new CurrencyHandle().addCurrency(playerCode, reason, rewards);
		task.setReward(true);
		task.set();

		TaskPublisher.getInstance().publish(playerCode);
		return rewards;
	}

}
